<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <div class="math-icon">🎓</div>
        <h1>加入我们</h1>
        <p>开始你的数学学习之旅</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="formData"
        :rules="rules"
        class="register-form"
        label-position="top"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="formData.agreeTerms"
            >我同意 <a href="#" class="terms-link">服务条款</a> 和
            <a href="#" class="terms-link">隐私政策</a></el-checkbox
          >
        </div>

        <el-form-item>
          <el-button
            type="primary"
            class="register-btn"
            :loading="isLoading"
            @click="handleRegister"
          >
            {{ isLoading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="register-footer">
        <p>已有账号？</p>
        <router-link to="/login" class="login-link">立即登录</router-link>
      </div>

      <div class="math-decoration">
        <div class="math-symbol">∫</div>
        <div class="math-symbol">√</div>
        <div class="math-symbol">θ</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const registerFormRef = ref<FormInstance>()
const authStore = useAuthStore()

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false,
})

// 表单状态
const isLoading = computed(() => authStore.isLoading)

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule, value: string, callback) => {
        if (!value) return callback(new Error('请确认密码'))
        if (value !== formData.password) return callback(new Error('两次输入的密码不一致'))
        callback()
      },
      trigger: ['blur', 'change'],
    },
  ],
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    if (!formData.agreeTerms) {
      ElMessage.warning('请先同意服务条款和隐私政策')
      return
    }

    // 使用认证store进行注册
    const success = await authStore.register({
      username: formData.username,
      email: formData.email,
      password: formData.password,
      confirmPassword: formData.confirmPassword,
    })

    if (success) {
      // 注册成功后跳转到登录页
      ElMessageBox.alert('注册成功！现在去登录吧！', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/login')
        },
      })
    } else {
      // 错误信息已经在store中处理
      ElMessage.error(authStore.error || '注册失败，请检查表单信息')
    }
  } catch (error) {
    console.error('注册失败:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('注册失败，请检查表单信息')
    }
  }
}

// 监听错误状态变化
watch(
  () => authStore.error,
  (newError) => {
    if (newError) {
      ElMessage.error(newError)
      authStore.clearError()
    }
  },
)
</script>

<style lang="less" scoped>
// 变量定义
@primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
@text-primary: #333;
@text-secondary: #666;
@white: #fff;
@shadow: 0 16px 32px rgba(0, 0, 0, 0.1);
@border-radius: 16px;
@transition: all 0.3s ease;
@error-color: #e74c3c;
@input-border: #e1e5e9;
@input-bg: #f8f9fa;

.register-container {
  height: calc(100vh - 126px);
  min-height: 100%; // 改为100%避免与外层导航叠加
  display: flex;
  align-items: center;
  justify-content: center;
  background: @primary-gradient;
  padding: 16px;

  .register-card {
    background: @white;
    border-radius: @border-radius;
    padding: 28px;
    width: 100%;
    max-width: 420px;
    box-shadow: @shadow;
    position: relative;
    overflow: hidden;

    .register-header {
      text-align: center;
      margin-bottom: 20px;

      .math-icon {
        font-size: 2.4rem;
        margin-bottom: 10px;
      }

      h1 {
        color: @text-primary;
        font-size: 1.5rem;
        margin-bottom: 6px;
        font-weight: 600;
      }

      p {
        color: @text-secondary;
        font-size: 0.92rem;
      }
    }

    .register-form {
      margin-bottom: 16px;

      .form-group {
        margin-bottom: 14px;

        label {
          display: block;
          margin-bottom: 6px;
          color: @text-primary;
          font-weight: 500;
          font-size: 0.9rem;
        }

        .input-wrapper {
          position: relative;
          display: flex;
          align-items: center;

          .input-icon {
            position: absolute;
            left: 10px;
            font-size: 1.1rem;
            color: #999;
            z-index: 1;
          }

          input {
            width: 100%;
            padding: 10px 10px 10px 38px;
            border: 2px solid @input-border;
            border-radius: 8px;
            font-size: 1rem;
            transition: @transition;
            background: @input-bg;

            &:focus {
              outline: none;
              border-color: #667eea;
              background: @white;
              box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }

            &.error {
              border-color: @error-color;
              background: #fdf2f2;
            }
          }

          .password-toggle {
            position: absolute;
            right: 10px;
            background: none;
            border: none;
            font-size: 1.1rem;
            cursor: pointer;
            color: #999;
            padding: 0;
            z-index: 1;
          }
        }

        .error-message {
          color: @error-color;
          font-size: 0.8rem;
          margin-top: 4px;
          display: block;
        }
      }

      .form-options {
        margin-bottom: 16px;

        .checkbox-wrapper {
          display: flex;
          align-items: flex-start;
          cursor: pointer;
          font-size: 0.9rem;
          color: @text-secondary;
          line-height: 1.4;

          input[type='checkbox'] {
            display: none;
          }

          .checkmark {
            width: 18px;
            height: 18px;
            border: 2px solid #ddd;
            border-radius: 4px;
            margin-right: 8px;
            margin-top: 2px;
            position: relative;
            transition: @transition;
            flex-shrink: 0;
          }

          input[type='checkbox']:checked + .checkmark {
            background: #667eea;
            border-color: #667eea;

            &::after {
              content: '✓';
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              color: @white;
              font-size: 12px;
              font-weight: bold;
            }
          }
        }

        .terms-link {
          color: #667eea;
          text-decoration: none;
          transition: @transition;

          &:hover {
            color: #5a6fd8;
          }
        }
      }

      .register-btn {
        width: 100%;
        height: 40px;
        background: @primary-gradient;
        color: @white;
        border: none;
        border-radius: 8px;
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
        transition: @transition;
        position: relative;

        &:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        &:disabled {
          opacity: 0.7;
          cursor: not-allowed;
        }

        .loading-spinner {
          animation: spin 1s linear infinite;
        }
      }
    }

    .register-footer {
      text-align: center;
      margin-top: 20px;

      p {
        color: @text-secondary;
        margin-bottom: 6px;
      }

      .login-link {
        color: #667eea;
        text-decoration: none;
        font-weight: 600;
        transition: @transition;

        &:hover {
          color: #5a6fd8;
        }
      }
    }

    .math-decoration {
      position: absolute;
      top: 0;
      right: 0;
      width: 80px;
      height: 80px;
      opacity: 0.06;
      pointer-events: none;

      .math-symbol {
        position: absolute;
        font-size: 1.5rem;
        color: #667eea;

        &:nth-child(1) {
          top: 12px;
          right: 12px;
        }

        &:nth-child(2) {
          top: 36px;
          right: 36px;
        }

        &:nth-child(3) {
          top: 60px;
          right: 12px;
        }
      }
    }
  }
}

// 动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .register-container {
    .register-card {
      padding: 22px 16px;
      margin: 12px;

      .register-header h1 {
        font-size: 1.35rem;
      }

      .checkbox-wrapper {
        font-size: 0.8rem;
      }
    }
  }
}
</style>
